<template>
  <div class="PositionLayout">
    <!-- 标题 -->
    <Title>
      <template #default>{{ title }}</template>
    </Title>
    <!-- 内容区 -->
    <section class="contentLayout" v-loading="loading">
      <div class="position">
        <div class="tableSet">
          <div>
            <button class="addI0" @click="open('addFather')">
              <span class="iconPlus">
                <el-icon><Plus /></el-icon>
              </span>
              <span class="text">新建</span>
            </button>
          </div>
          <div>
            <el-tooltip content="刷新" placement="top">
              <el-icon size="19" @click="Refresh">
                <RefreshRight />
              </el-icon>
            </el-tooltip>
          </div>
          <div>
            <el-tooltip content="密度" placement="top">
              <el-dropdown ref="dropdown1" trigger="contextmenu" @command="hCommand($event)">
                <el-icon size="19" @click="GapSize"><Sort /></el-icon>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="default">{{ textSize[0] }}</el-dropdown-item>
                    <el-dropdown-item command="midden">{{ textSize[1] }}</el-dropdown-item>
                    <el-dropdown-item command="small">{{ textSize[2] }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-tooltip>
          </div>
          <div>
            <el-tooltip content="列设置" placement="top">
              <div>
                <el-popover placement="bottom-start" :width="200" trigger="click">
                  <template #reference>
                    <el-icon size="19" @click="setHeader"><Setting /></el-icon>
                  </template>
                  <el-tree ref="treeRef" style="max-width: 600px" :data="headerList"
                           show-checkbox node-key="id" default-expand-all :expand-on-click-node="false"
                           check-on-click-node @check-change="nodeChange" :default-checked-keys="headerTableList"
                           :props="{children: 'children',label: 'label',}"
                  />
                </el-popover>
              </div>
            </el-tooltip>
          </div>
        </div>
        <div class="positionTable">
          <el-table :data="tabledata" style="width: 100%" table-layout="fixed" row-key="id" :size="tableSize">
            <el-table-column prop="index" label="序号" width="100" v-if="headerTableList.indexOf(1)!==-1"/>
            <el-table-column prop="name" label="名称" width="340" v-if="headerTableList.indexOf(2)!==-1"/>
            <el-table-column prop="createdAt" label="创建时间" width="440" v-if="headerTableList.indexOf(10)!==-1"/>
            <el-table-column label="操作" width="420" v-if="headerTableList.indexOf(11)!==-1">
              <template #default="scope">
                <el-button link type="primary" size="small" class="del" @click="open('addSon', scope.row)" v-if="scope.row.level != 2">
                  新增子类
                </el-button>
                <el-button link type="primary" size="small" class="del" @click="updatePositionName(scope.row)">
                  编辑
                </el-button>
                <el-button link type="primary" size="small" class="del" @click="deletePositionName(scope.row)" v-if="!scope.row.children.length">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页组件 -->
        <div class="example-pagination-block pageCom">
          <div class="example-demonstration">
            第 1-{{ pagesObj.total }} 条/总共 {{ pagesObj.total }} 条
          </div>
          <el-pagination layout="prev, pager, next" :total="pagesObj.total" :page-size="pagesObj.per_page" size="small" :current-page="currentPage" @current-change="currentChange"/>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import Title from "components/public/Title";
import { useRoute } from "vue-router";
import { getAddPosition,getPositionList,UpdatePosition,DeletePosition } from "@/network/position";
import { onMounted, ref } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { Plus, RefreshRight, Setting, Sort} from "@element-plus/icons-vue";

const route = useRoute();
const title = route.meta.title;

onMounted(()=>{
  getPosition();
})

const tabledata = ref([]);
const list = ref([]);
const pagesObj = ref([]);

const getPosition = async () => {
  loading.value = true;
  // 获取数据
  const res = await getPositionList(currentPage.value);
  pagesObj.value = res.data.meta;
  list.value = res.data.data.list;
  // 格式化时间
  list.value.forEach((v) => {
    v.createdAt = v.createdAt.slice(0, 19).replace("T", " ");
  });
  // pagesObj.value = res.data.meta;
  // list.value = res.data.data.list;
  // 格式化时间
  // list.value.forEach((v) => {
  //   v.createdAt = v.createdAt.slice(0, 19).replace("T", " ");
  // });
  // 初始化 tabledata，按 level 分类
  let tempArr = ref([]);
  tempArr.value = list.value.filter(v => v.level === 0).map((v, index) => ({
    ...v,
    index: index + 1,
    children: []
  }));
  // 将 level 1 和 level 2 的数据添加到对应的父级 children 中
  list.value.forEach((v) => {
    if (v.level === 1) {
      const parent = tempArr.value.find(item => item.id === v.pid);
      if (parent) {
        parent.children.push({
          ...v,
          children: [],
          index: parent.children.length + 1,
        });
      }
    } else if (v.level === 2) {
      for (let parent of tempArr.value) {
        const child = parent.children.find(item => item.id === v.pid);
        if (child) {
          child.children.push({
            ...v,
            children: [],
            index: child.children.length + 1,
          });
        }
      }
    }
  });
  // 更新所有子项的 index
  const updateIndex = (data) => {
    data.forEach((item, idx) => {
      item.index = idx + 1;
      if (item.children.length > 0) {
        updateIndex(item.children);
      }
    });
  };
  updateIndex(tempArr.value);
  tabledata.value = tempArr.value;
  loading.value = false;
};

const loading = ref(false);
const Refresh = () => {
  loading.value = true;
  getPosition();
};

const dropdown1 = ref();
const tableSize = ref("default");
const GapSize = () => {
  if (!dropdown1) return;
  dropdown1.value.handleOpen();
};
const textSize = ref(["默认", "中等", "紧凑"]);
function hCommand(e) {
  if (e == "default") {
    tableSize.value = "large";
    textSize.value = ["默认", "中等", "紧凑"];
  } else if (e == "midden") {
    tableSize.value = "default";
    textSize.value = ["默认", "中等", "紧凑"];
  } else if (e == "small") {
    tableSize.value = "small";
    textSize.value = ["默认", "中等", "紧凑"];
  } else {
    tableSize.value = "";
  }
}
const setHeader = () => {
  console.log("表头的展示与隐藏");
};
const treeRef = ref();
const headerTableList = ref([1, 2, 10, 11]);
const headerList = [
  {
    id: 0,
    label: "列设置",
    children: [
      {
        id: 30,
        label: "不固定",
        children: [
          {
            id: 1,
            label: "序号",
          },
          {
            id: 2,
            label: "名称",
          },
          {
            id: 10,
            label: "编辑时间",
          },
          {
            id: 11,
            label: "操作",
          },
        ],
      },
    ],
  },
];

const nodeChange = (obj) => {
  headerTableList.value = treeRef.value.getCheckedKeys();
};

const open = (action, row) => {
  ElMessageBox.prompt("岗位名称", "添加岗位", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /([A-z]|[\u4e00-\u9fa5]){2,}/,
    inputErrorMessage: "请输入正确的岗位名称",
    inputPlaceholder: "请输入岗位名称",
    customClass: "addMessageBox",
  })
      .then(async ({ value }) => {
        if (value) {
          if (action == "addFather") {
            await getAddPosition({
              name: value,
            });
          } else if (action == "addSon") {
            // 新增子类
            await getAddPosition({
              name: value,
              pid: row.id,
            });
          } else {
            return;
          }
          Refresh();
        } else {
          return;
        }

        ElMessage({
          type: "success",
          message: `成功添加岗位:${value}`,
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消操作",
        });
      });
};

const updatePositionName = (row) => {
  ElMessageBox.prompt("岗位名称", "编辑岗位", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /([A-z]|[\u4e00-\u9fa5]){2,}/,
    inputErrorMessage: "请输入正确的岗位名称",
    inputPlaceholder: "请输入岗位名称",
    customClass: "addMessageBox",
  })
      .then(async ({ value }) => {
        if (value) {
          if (row) {
            await UpdatePosition({
              name: value,
              id: row.id,
            });
          } else {
            return;
          }
          Refresh();
        } else {
          return;
        }
        ElMessage({
          type: "success",
          message: `成功添加岗位:${value}`,
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消操作",
        });
      });
};

const deletePositionName = (row) => {
  ElMessageBox.confirm('确定删除 "' + row.name + '" 吗?', "删除岗位信息", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    customClass: "deleteMessageBox",
  })
      .then(async () => {
        await DeletePosition(row.id);
        Refresh();
        ElMessage({
          type: "success",
          message: "成功删除" + row.name,
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消操作",
        });
      });
};

const currentPage = ref(3); // 当前页数
const currentChange = (page) => {
  currentPage.value = page;
  Refresh();
};

</script>

<style lang="scss">
.position{
  background-color: white;
  padding: 0 24px;
}
.tableSet {
  padding: 16px 0;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  & > div {
    padding: 8px;
    .el-dropdown {
      color: var(--color-text);
    }
    .addI0 {
      padding: 6px 15px;
      color: #fff;
      background: var(--color-high-text);
      border: 1px solid var(--color-high-text);
      border-radius: 5%;
      display: flex;
      justify-content: space-between;
      .iconPlus {
        padding-top: 1px;
      }
      .text {
        padding-left: 8px;
      }
    }
  }
}
.pageCom {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 16px;
  li.is-active {
    border: 1px solid var(--color-high-text);
    font-weight: 500;
  }
  .number {
    font-size: 14px;
  }
}
.el-overlay-message-box {
  top: -200px !important;

  .el-message-box.addMessageBox {
    --el-messagebox-width: 640px;
    height: 243px;
    padding: 0;
    // 头部标题
    .el-message-box__header {
      padding: 0 !important;
      border-bottom: 1px solid var(--border-color-tint);

      .el-message-box__title {
        padding: 16px 24px;
        font-size: 16px;
        color: var(--color-text) !important;
      }
      .el-message-box__headerbtn {
        width: 54px;
        height: 54px;
        .el-message-box__close {
          font-size: 20px;
        }
      }
    }
    // 输入内容
    .el-message-box__content {
      padding: 24px;
      margin-bottom: 24px;
      .el-message-box__message {
        color: var(--color-text) !important;
      }
    }
    .el-message-box__btns {
      border-top: 1px solid var(--border-color-tint);
      padding: 10px 16px;
    }
  }
}
</style>